package com.example.controller;

import com.example.pojo.Goods;
import com.example.pojo.Order;
import com.example.service.GoodsService;
import com.example.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.List;

/**
 * @author BeauFang
 * Date: 2020/8/12
 */
@Controller
public class IndexController {
    @Autowired
    private GoodsService goodsService;

    @Autowired
    private OrderService orderService;

    @RequestMapping("/")
    public String index(Model model) {
        List<Goods> goods = goodsService.findAll();
        model.addAttribute("goods", goods);
        return "index";
    }

    /**
     * 提交订单，将订单写入消息队列，跳转到支付页面
     * @param model
     * @param id
     * @return
     */
    @RequestMapping(value = "/submitOrder", method = RequestMethod.POST)
    public String submitOrder(Model model, String id) {
        Order order = new Order();
        order.setGoodsId(id);
        order.setCreateTime(System.currentTimeMillis());
        order.setState(Order.STATE.UNPAY);
        orderService.submit(order);
        model.addAttribute("order", order);
        return "pay";
    }

    @RequestMapping("/orderList")
    public String orderList(Model model) {
        List<Order> orderList = orderService.findAll();
        model.addAttribute("orderList", orderList);
        return "orderList";
    }

    @RequestMapping("/pay")
    public String pay(String id) {
        Order order = orderService.findById(id);
        if (order != null) {
            order.setState(Order.STATE.FINISHED);
        }
        orderService.save(order);
        return "redirect:orderList";
    }
}
